package com.wzx.mvc.utils;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ClassUtil {


    /**
     * 获取这个包下所有的类
     * @param packStr
     * @return
     */
    public static List<Class> getAllClass(String packStr) throws URISyntaxException {
        ClassLoader classLoader = ClassUtil.class.getClassLoader();
        URL resource = classLoader.getResource("");

        Path path = Paths.get(resource.toURI());
        String packageDir = packStr.replaceAll("\\.", File.separator + File.separator);
        List<String> className = getClassName(path.resolve(packageDir), packStr);

        return className.stream().map(cls -> {
            try {
                return Class.forName(cls);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
    }

    public static List<String> getClassName(Path classesDir, String packStr) {
        List<String> classNameList = new ArrayList<>();
        try {
            Files.newDirectoryStream(classesDir).forEach(item -> {
                if (Files.isDirectory(item)) {
                    String currDir = item.getFileName().toString();
                    classNameList.addAll(getClassName(classesDir.resolve(currDir), packStr + "." + currDir));
                    return;
                }
                String className = item.getFileName().toString();
                classNameList.add(packStr + "." + className.substring(0, className.indexOf(".")));
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classNameList;
    }

    public static String firstWordLower(String name) {
        return name.substring(0, 1).toLowerCase() + name.substring(1);
    }

    public static void main(String[] args) throws IOException, URISyntaxException {
        getAllClass("com.wzx");
    }
}
